package com.knowswift.issues.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.knowswift.common.bean.issue.group.AddGroup;
import com.knowswift.common.bean.issue.group.UpdateGroup;
import com.knowswift.common.bean.issue.po.Customer;
import com.knowswift.common.bean.issue.po.Issue;
import com.knowswift.common.bean.issue.po.MonitorRecord;
import com.knowswift.common.bean.issue.po.SysUser;
import com.knowswift.common.bean.issue.vo.*;
import com.knowswift.common.bean.project.po.Module;
import com.knowswift.common.bean.project.po.MonitorSetting;
import com.knowswift.common.bean.project.po.Project;
import com.knowswift.common.bean.project.vo.ModulePermissionVO;
import com.knowswift.common.bean.project.vo.ModuleVO;
import com.knowswift.common.bean.project.vo.MonitorSettingVO;
import com.knowswift.common.bean.project.vo.ProjectLimit;
import com.knowswift.common.common.Assert;
import com.knowswift.common.common.BaseResponse;
import com.knowswift.common.common.GlobalProperty;
import com.knowswift.common.common.Page;
import com.knowswift.common.enums.IssueStatus;
import com.knowswift.common.enums.RoleEnum;
import com.knowswift.common.utils.AliOSSUtil;
import com.knowswift.common.utils.JSONUtils;
import com.knowswift.common.utils.WrappedBeanCopier;
import com.knowswift.issues.util.MonitorUtil;
import com.knowswift.log.aop.AopLog;
import com.knowswift.security.account.User;
import com.knowswift.security.account.UserService;
import com.knowswift.security.util.AllowVisitor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;


@RestController
@RequestMapping("/admin/issue/")
@Slf4j
public class AdminIssueController extends AbstractController {

    @PostMapping("/issues")
    @AopLog(saveLog = false, name = "上报列表", platform = "管理后台")
    public BaseResponse issues(@AuthenticationPrincipal User user, @RequestBody IssueVO param) {
        log.info("当前的服务是：/admin/issue-new/");
        Page<IssueVO> page = new Page<>(param.getPageNo(), param.getPageSize());
        // 判断用户是否有查看全部数据的权限
        boolean allIssues = UserService.checkAuthority(user, "allIssues");
        boolean ownIssues = UserService.checkAuthority(user, "ownIssues");
        boolean projectIssues = UserService.checkAuthority(user, "projectIssues");
        String userId = allIssues || projectIssues ? null : user.getUserId();
        List<String> strings = null;

        if (!allIssues && !ownIssues && projectIssues) {
            strings = new ArrayList<>();
            List<ModulePermissionVO> permissions = modulePermissionService.getBaseMapper().getByUserId(user.getUserId());
            for (ModulePermissionVO permission : permissions) {
                List<ProjectLimit> projectLimits = WrappedBeanCopier.JSONArrayToList(permission.getProjects(), ProjectLimit.class);
                for (ProjectLimit projectLimit : projectLimits) {
                    if (BooleanUtils.isTrue(projectLimit.getLimit())) {
                        strings.add(permission.getModuleName() + projectLimit.getProjectName());
                    }
                }

            }
        }
        page = issueService.getBaseMapper().getRecordsInAdmin(userId, param.getModuleName(), param.getProjectName(),
                param.getIssueArea(), param.getIssueCode(), param.getIssueStatus(), strings, page);
        return BaseResponse.success(page);
    }

    @PostMapping("/issueDetails")
    @AopLog(saveLog = false, name = "上报详情", platform = "管理后台")
    public BaseResponse issueDetails(@RequestBody IssueVO param) {
        Issue issue = issueService.getById(param.getIssueId());
        return BaseResponse.success(issue);
    }

    @PostMapping("/relations")
    @AopLog(name = "关联的上报记录", platform = "管理后台")
    public BaseResponse relations(@RequestBody IssueVO param) {
        Issue issue = issueService.getById(param.getIssueId());
        Assert.notNull(issue, "数据不存在");
        Page<Issue> page = new Page<>(param.getPageNo(), param.getPageSize());
        page = issueService.lambdaQuery()
                .eq(Issue::getModuleName, issue.getModuleName())
                .eq(Issue::getProjectName, issue.getProjectName())
                .eq(Issue::getIssueArea, issue.getIssueArea())
                .eq(Issue::getIssueCode, issue.getIssueCode())
                .ne(Issue::getIssueId, issue.getIssueId())
                .eq(Issue::getIssueStatus, IssueStatus.PASS.getValue())
                .select(Issue::getIssueId, Issue::getReportTime, Issue::getIssueImages)
                .page(page);
        return BaseResponse.success(page);
    }

    @PostMapping("/areaAndCodes")
    @AopLog(saveLog = false, name = "区域和编号列表", platform = "管理后台")
    public BaseResponse areaAndCodes(@RequestBody IssueVO param) {
        List<Issue> list = issueService.lambdaQuery().eq(Issue::getModuleName, param.getModuleName())
                .eq(Issue::getProjectName, param.getProjectName()).select(Issue::getIssueArea, Issue::getIssueCode)
                .orderByDesc(Issue::getReportTime)
                .list();
        List<String> areas = new ArrayList<>();
        List<String> codes = new ArrayList<>();
        for (Issue issue : list) {
            if (!areas.contains(issue.getIssueArea())) {
                areas.add(issue.getIssueArea());
            }
            if (!codes.contains(issue.getIssueCode())) {
                if (StringUtils.isBlank(param.getIssueArea()) || param.getIssueArea().equals(issue.getIssueArea())) {
                    codes.add(issue.getIssueCode());
                }
            }
        }
        HashMap<String, List<String>> map = new HashMap<>();
        map.put("areas", areas);
        map.put("codes", codes);
        return BaseResponse.success(map);
    }

    @PostMapping("/audit")
    @PreAuthorize("@userService.checkAuthority('auditIssue')")
    @AopLog(name = "审核", platform = "管理后台")
    public BaseResponse audit(@AuthenticationPrincipal User user, @RequestBody IssueVO param) {
        Assert.notBlank(param.getIssueId(), "请选择审核的记录");
        Assert.notNull(param.getIssueStatus(), "请选择审核结果");
        // 尝试抢锁
        String key = param.getIssueId() + "auditLock";
        boolean b = redisUtils.setNx(key, 1, 5);
        int i = 100;
        while (!b) {
            // 抢不到锁则再次尝试
            b = redisUtils.setNx(key, 1, 5);
            i--;
            if (i < 0) {
                break;
            }
        }
        if (!b) {
            return BaseResponse.failure("服务器忙，请重试");
        }
        Issue issue = issueService.getById(param.getIssueId());
        Assert.notNull(issue, "数据不存在");
        Assert.isTrue(!issue.getIssueStatus().equals(IssueStatus.PASS.getValue()), "已经审核通过，不可重复审核");
        issue.setAuditUserId(user.getUserId());
        issue.setAuditTime(LocalDateTime.now());
        issue.setIssueStatus(param.getIssueStatus());
        if (param.getIssueStatus().equals(IssueStatus.PASS.getValue()) || param.getIssueStatus().equals(IssueStatus.REJECT.getValue())) {
            boolean update = issueService.updateById(issue);
            Assert.isTrue(update, "审核失败");
        } else {
            return BaseResponse.failure("请选择通过或者未通过");
        }
        redisUtils.del(key);
        asyncTask.saveAuditMassage(issue);
        return BaseResponse.success();
    }

    @PostMapping("/deleteIssue")
    @AopLog(name = "删除上报记录", platform = "管理后台")
    public BaseResponse deleteIssue(@AuthenticationPrincipal User user, @RequestBody IssueVO param) {
        Issue issue = issueService.getById(param.getIssueId());
        Assert.notNull(issue, "数据不存在");
        boolean newIssue = issue.getIssueStatus().equals(IssueStatus.NEW.getValue());
        if (newIssue) {
            // 未审核的，有权限可以删除
            boolean editIssue = UserService.checkAuthority(user, "editIssue");
            Assert.isTrue(editIssue, "无权操作");
        } else {
            // 已审核的，超级管理员才可以删除
            Assert.isTrue(user.getRole().equals(RoleEnum.ROLE_ADMIN.name()), "无权操作");
        }
        boolean remove = issueService.removeById(param.getIssueId());
        return BaseResponse.condition(remove, "删除失败");
    }

    @PostMapping("/updateIssue")
    @PreAuthorize("@userService.checkAuthority('editIssue')")
    @AopLog(name = "修改上报记录", platform = "管理后台")
    public BaseResponse updateIssue(@Validated @RequestBody IssueVO param) {
        Issue issue = WrappedBeanCopier.copyProperties(param, Issue.class);
        issue.setIssueStatus(IssueStatus.NEW.getValue());
        boolean update = issueService.updateById(issue);
        return BaseResponse.condition(update, "修改失败");
    }

    @PostMapping("/getOssToken")
    @PreAuthorize("@userService.checkAuthority('editIssue')")
    @AopLog(name = "获取上传token", platform = "管理后台")
    public BaseResponse getOssToken() {
        Object ossToken = AliOSSUtil.getOSSToken();

        System.out.println("===========================oss>"+ossToken);
        return BaseResponse.success(ossToken);
    }

    @RequestMapping("/ossBack")
    @AllowVisitor(checkToken = false)
    @AopLog(name = "OSS回调", platform = "管理后台")
    public void ossBack(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String ossCallbackBody = AliOSSUtil.GetPostBody(request.getInputStream(),
                Integer.parseInt(request.getHeader("content-length")));
//        filename=baddymate%2Fimage%2F51a981fb24b93c733c9f1e39678c9af0.jpg&size=81977&mimeType=image%2Fjpeg&height=336&width=610
        boolean ret = false;
        try {
            ret = AliOSSUtil.VerifyOSSCallbackRequest(request, ossCallbackBody);
        } catch (NumberFormatException | IOException e) {
//            SystemLog systemLog = new SystemLog();
//            systemLog.setException(e.getMessage());
//            systemLog.setType("异常");
//            systemLog.setPath("/ossBack");
//            systemLog.setName("阿里云上传回调");
//            systemLog.setParam("{\"request\":\"" + request + "\"}");
//            systemLogService.saveLog(systemLog);
        }
        if (ret) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("Status", "OK");
            String[] split = ossCallbackBody.split("&");
            for (String s1 : split) {
                String[] split1 = s1.split("=");
                String key = split1[0];
                String value = split1[1];
                if (key.equals("filename")) {
                    value = AliOSSUtil.getHost() + "/" + URLDecoder.decode(value, StandardCharsets.UTF_8.name());
                }
                map.put(key, value);
            }
            String results = JSONUtils.toJSONString(map);
            AliOSSUtil.response(request, response, results, HttpServletResponse.SC_OK);
        } else {
            AliOSSUtil.response(request, response, "{\"Status\":\"verdify not ok\"}", HttpServletResponse.SC_BAD_REQUEST);
        }
    }

    @PostMapping("/modules")
    @PreAuthorize("@userService.checkAuthority('allIssues','ownIssues','projectIssues')")
    @AopLog(name = "模块列表", platform = "管理后台")
    public BaseResponse modules(@AuthenticationPrincipal User user, @RequestBody ModuleVO param) {
        Page<ModuleVO> page = new Page<>(param.getPageNo(), param.getPageSize());
        boolean allIssues = UserService.checkAuthority(user, "allIssues");
        boolean ownIssues = UserService.checkAuthority(user, "ownIssues");
        boolean projectIssues = UserService.checkAuthority(user, "projectIssues");
        if (!allIssues && !ownIssues && projectIssues) {
            Page<ModulePermissionVO> voPage = modulePermissionService.getBaseMapper().getByUserIdPage(user.getUserId(), page);
            modulePermissionService.concatData(voPage.getRecords());
            return BaseResponse.success(voPage);
        }
        page = moduleService.findIssueModuleList(param.getKeyword(), 0, page);
        return BaseResponse.success(page);
    }

    @GetMapping("/getTest")
    @AopLog(name = "getTest", platform = "getTest")
    @AllowVisitor(checkToken = false)
    public String  getTest() {
        log.info("测试getTest");
        return "OK";
    }

    //region 项目接口

    @AopLog(saveLog = false, name = "查询客户分页", platform = "管理后台")
    @GetMapping("/moduleList")
    @AllowVisitor(checkToken = false)
    public BaseResponse moduleList() {
      List<Module>  list = moduleService.getmoduleList();
        return BaseResponse.success(list);
    }

    //endregion


    //region 客户接口
    @AopLog(saveLog = false, name = "查询客户分页", platform = "管理后台")
    @PostMapping("/page")
    @AllowVisitor(checkToken = false)
    public BaseResponse queryPage(@RequestBody CustomerVO param) {
        Page<IssueVO> page = new Page<>(param.getPageNo(), param.getPageSize());
        page = customerService.getBaseMapper().getCustomers(param.getCustomerCode(), param.getCustomerName(),
                param.getStatus(), page);
        return BaseResponse.success(page);
    }

    //@AopLog(saveLog = false, name = "查询客户详情", platform = "管理后台")
    @GetMapping("/customerInfo/{customerId}")
    @AllowVisitor(checkToken = false)
    public BaseResponse customerInfo(@PathVariable("customerId") String customerId) {
        Customer customer = customerService.getById(customerId);
        if(customer==null){
            return BaseResponse.failure("未查询到id为"+customerId+"的客户");
        }
        //获取客户账号
        List<SysUser> userList = sysUserService.getBaseMapper().getUserByCustomerId(customerId);
        customer.setUserList(userList);
        List<ModuleDto> moduleDtoList = authorizeService.getBaseMapper().getModuleByCustomerId(customerId);
        //获取客户授权项目
        for (ModuleDto module : moduleDtoList) {
            List<Project> projectList = authorizeService.getBaseMapper().getCustomerModuleProject(customerId, module.getModuleId());
            module.setProjects(projectList);
        }
        customer.setModuleList(moduleDtoList);
        return BaseResponse.success(customer);
    }



    @AopLog(saveLog = false, name = "新增客户", platform = "管理后台")
    @PostMapping("/saveCustomer")
    @AllowVisitor(checkToken = false)
    public BaseResponse saveCustomer(@Valid @RequestBody Customer customer) {

        customerService.saveCustomer(customer);
        return BaseResponse.success("新增成功");
    }

    @AopLog(saveLog = false, name = "修改客户", platform = "管理后台")
    @PostMapping("/updateCustomer")
    @AllowVisitor(checkToken = false)
    public BaseResponse updateCustomer(@Valid @RequestBody Customer customer) {
        //customerService.getbyCustomerName(customer.getCustomerName());
        customerService.updateById(customer);
        return BaseResponse.success("修改成功");
    }

    @AopLog(saveLog = false, name = "启用客户", platform = "管理后台")
    @GetMapping("/enableCustomer")
    @AllowVisitor(checkToken = false)
    public BaseResponse enableCustomer(String customerId) {
     Customer customer = customerService.getById(customerId);
     customer.setStatus(1);
        customerService.updateById(customer);
        return BaseResponse.success("启用客户成功");
    }
    @AopLog(saveLog = false, name = "停用客户", platform = "管理后台")
    @GetMapping("/disableCustomer")
    @AllowVisitor(checkToken = false)
    public BaseResponse disableCustomer(String customerId) {
        Customer customer = customerService.getById(customerId);
        customer.setStatus(0);
        customerService.updateById(customer);
        return BaseResponse.success("停用客户成功");
    }

    @AopLog(saveLog = false, name = "删除客户", platform = "管理后台")
    @DeleteMapping("/deleteCustomer")
    @AllowVisitor(checkToken = false)
    public BaseResponse deleteCustomer(@RequestBody String[] customerIds) {
        for (String id : customerIds){
            List<SysUser> userList = sysUserService.getBaseMapper().getUserByCustomerId(id);
            if(userList!=null&&userList.size()>0){
                return BaseResponse.failure("id为"+id+"的客户下有账户无法删除");
            }
        }
        customerService.removeByIds(Arrays.asList(customerIds));
        return BaseResponse.success("删除成功");
    }
    @AopLog(saveLog = false, name = "授权客户项目", platform = "管理后台")
    @PostMapping("/Auth")
    @AllowVisitor(checkToken = false)
    public BaseResponse ProjectAuthorize(@RequestParam String customerId, @RequestBody List<ModuleDto> moduleList){
        Customer customer = customerService.getById(customerId);
        if(customer==null){
            return BaseResponse.failure("未查询到id为"+customerId+"的客户");
        }
        customerService.ProjectAuthorize(customerId,moduleList);
        return BaseResponse.success("授权成功");
    }

    //endregion

    //region 客户账户接口
    @AopLog(saveLog = false, name = "查询客户账户分页", platform = "管理后台")
    @PostMapping("/userPage")
    @AllowVisitor(checkToken = false)
    public BaseResponse queryUserPage(@RequestBody CustomerVO param) {
        Page<SysUserVo> page = new Page<>(param.getPageNo(), param.getPageSize());
        page = sysUserService.getBaseMapper().getUsers( param.getCustomerId(),param.getUsername(), page);
        return BaseResponse.success(page);
    }
    @AopLog(saveLog = false, name = "查询客户账户详情", platform = "管理后台")
    @GetMapping("/info/{userId}")
    @AllowVisitor(checkToken = false)
    public BaseResponse userInfo(@PathVariable("userId") Long userId) {
        SysUser user = sysUserService.getById(userId);
        if(user==null){
            return BaseResponse.failure("未查询到id为"+userId+"的客户账户");
        }
        SysUserVo sysUser = new SysUserVo();
        BeanUtils.copyProperties(user, sysUser);  // 复制同名字段（自动忽略类型不匹配的字段）
        sysUser.setUserId(user.getUserId().toString());  // 手动处理特殊字段


        //获取客户账户授权项目
        List<ModuleDto> moduleDtoList = authorizeService.getBaseMapper().getModuleByUserId(userId);
        for (ModuleDto module : moduleDtoList) {
            List<Project> projectList = authorizeService.getBaseMapper().getUserModuleProject(userId, module.getModuleId());
            module.setProjects(projectList);
        }
        sysUser.setModuleList(moduleDtoList);
        return BaseResponse.success(sysUser);
    }



    @AopLog(saveLog = false, name = "新增客户账户", platform = "管理后台")
    @PostMapping("/saveUser")
    @AllowVisitor(checkToken = false)
    public BaseResponse saveUser(@Validated(AddGroup.class) @RequestBody SysUser user) {

        SysUser sysUser = sysUserService.queryByUserName(user.getUsername());
        if(sysUser!=null){
            return BaseResponse.failure("已存在名称为"+user.getUsername()+"的客户账户");
        }

    if(StringUtils.isBlank(user.getCustomerId())){
        Customer customer = customerService.getBaseMapper().getCustomerById(user.getCustomerId());
        if(customer==null){
            return BaseResponse.failure("未查询到id为"+user.getCustomerId()+"的客户或者该客户已被停用");
        }
    }
        sysUserService.saveUser(user);
        return BaseResponse.success("新增成功");
    }

    @AopLog(saveLog = false, name = "修改客户账户", platform = "管理后台")
    @PostMapping("/updateUser")
    @AllowVisitor(checkToken = false)
    public BaseResponse updateUser(@Validated(UpdateGroup.class) @RequestBody SysUser user) {
        if(StringUtils.isBlank(user.getCustomerId())){
            Customer customer = customerService.getBaseMapper().getCustomerById(user.getCustomerId());
            if(customer==null){
                return BaseResponse.failure("未查询到id为"+user.getCustomerId()+"的客户或者该客户已被停用");
            }
        }
        SysUser sysUser = sysUserService.getById(user.getUserId());
        if(sysUser==null){
            return BaseResponse.failure("未查询到id为"+user+"的客户账户");
        }
        if(StringUtils.isBlank(user.getPassword())){
            sysUser.setPassword(null);
        }else{
            user.setPassword(new Sha256Hash(user.getPassword(), sysUser.getSalt()).toHex());
        }
        sysUserService.updateById(user);
        return BaseResponse.success("修改成功");
    }
    @AopLog(saveLog = false, name = "启用客户", platform = "管理后台")
    @GetMapping("/enableUser")
    @AllowVisitor(checkToken = false)
    public BaseResponse enableUser(Long userId) {
        SysUser user = sysUserService.getById(userId);
        if(user==null){
            return BaseResponse.failure("未查询到id为"+user+"的客户账户");
        }
        user.setStatus(1);
        sysUserService.updateById(user);
        return BaseResponse.success("启用客户成功");
    }
    @AopLog(saveLog = false, name = "停用客户账户", platform = "管理后台")
    @GetMapping("/disableUser")
    @AllowVisitor(checkToken = false)
    public BaseResponse disableUser(Long userId) {
        SysUser user = sysUserService.getById(userId);
        if(user==null){
            return BaseResponse.failure("未查询到id为"+user+"的客户账户");
        }
        user.setStatus(0);
        sysUserService.updateById(user);
        return BaseResponse.success("停用客户账户成功");
    }


    @AopLog(saveLog = false, name = "删除客户账户", platform = "管理后台")
    @DeleteMapping("/deleteUser")
    @AllowVisitor(checkToken = false)
    public BaseResponse deleteuser(@RequestBody Long[] UserIds) {
        sysUserService.removeByIds(Arrays.asList(UserIds));
        return BaseResponse.success("删除成功");
    }
    @AopLog(saveLog = false, name = "授权客户账户项目", platform = "管理后台")
    @PostMapping("/AuthUser")
    @AllowVisitor(checkToken = false)
    public BaseResponse ProjectUserAuthorize(@RequestParam Long userId, @RequestBody List<ModuleDto> moduleList){
        SysUser user = sysUserService.getById(userId);
        if(user==null){
            return BaseResponse.failure("未查询到id为"+user+"的客户账户");
        }
        sysUserService.ProjectAuthorize(userId,moduleList);
        return BaseResponse.success("授权成功");
    }
    @AopLog(saveLog = false, name = "重置密码", platform = "管理后台")
    @PostMapping("/resetPassword")
    @AllowVisitor(checkToken = false)
    public BaseResponse password(Long userId){
        SysUser user = sysUserService.getById(userId);
        if(user==null){
            return BaseResponse.failure("未查询到id为"+user+"的客户账户");
        }
        //sha256加密
        String password = new Sha256Hash("123456", user.getSalt()).toHex();
        user.setPassword(password);
        //更新密码
        sysUserService.updateById(user);

        return BaseResponse.success("更新成功");
    }

    //endregion



    //region 监控设置
    @PostMapping("/saveSetting")
    @AopLog(name = "保存监控设置", platform = "管理后台")
    @AllowVisitor(checkToken = false)
    @Transactional
    public BaseResponse saveSetting(@RequestBody @Validated SaveMonitorSettingParam param) {
        monitorSettingService.remove(new LambdaQueryWrapper<MonitorSetting>()
                .ne(MonitorSetting::getName, GlobalProperty.SETTING_NAME_ENABLE));
        MonitorSetting temperature = new MonitorSetting();
        temperature.setName(GlobalProperty.SETTING_NAME_TEMPERATURE);
        if (param.getTemperatureMin() != null && param.getTemperatureMax() != null) {
            Assert.isFalse(param.getTemperatureMin() >= param.getTemperatureMax(), "温度最小值大于或等于最大值");
        }
        temperature.setMin(param.getTemperatureMin());
        temperature.setMax(param.getTemperatureMax());
        temperature.setInvocation(param.getTemperatureInvocation());
        monitorSettingService.save(temperature);

        MonitorSetting humidity = new MonitorSetting();
        humidity.setName(GlobalProperty.SETTING_NAME_HUMIDITY);
        if (param.getHumidityMin() != null && param.getHumidityMax() != null) {
            Assert.isFalse(param.getHumidityMin() >= param.getHumidityMax(), "湿度最小值大于或等于最大值");
        }
        humidity.setMin(param.getHumidityMin());
        humidity.setMax(param.getHumidityMax());
        humidity.setInvocation(param.getHumidityInvocation());
        monitorSettingService.save(humidity);

        MonitorSetting electric = new MonitorSetting();
        electric.setName(GlobalProperty.SETTING_NAME_ELECTRICITY);
        if (param.getElectricityMin() != null && param.getElectricityMax() != null) {
            Assert.isFalse(param.getElectricityMin() >= param.getElectricityMax(), "电流最小值大于或等于最大值");
        }
        electric.setMin(param.getElectricityMin());
        electric.setMax(param.getElectricityMax());
        electric.setInvocation(param.getElectricityInvocation());
        monitorSettingService.save(electric);
        return BaseResponse.success();
    }

    @RequestMapping("/getSetting")
    @AllowVisitor(checkToken = false)
    //@PreAuthorize("hasRole('ROLE_ADMIN')")
    public BaseResponse getSetting() {
        List<MonitorSetting> list = monitorSettingService.list();
        MonitorSettingVO monitorSettingVO = MonitorUtil.getSetting(list);
//        MonitorSetting enable = temp.get(GlobalProperty.SETTING_NAME_ENABLE);
//        monitorSettingVO.setEnable(false);
//        if (enable != null) {
//            if (enable.getEnable() == 1) {
//                monitorSettingVO.setEnable(true);
//            }
//        } else {
//            enable = new MonitorSetting();
//            enable.setName(GlobalProperty.SETTING_NAME_ENABLE);
//            enable.setEnable(0); // 默认关闭
//            monitorSettingService.save(enable);
//        }

        return BaseResponse.success(monitorSettingVO);
    }
    //endregion



    //region 告警信息
    @GetMapping("/enableMonitorAlert")
    @AllowVisitor(checkToken = false)
    //@PreAuthorize("hasRole('ROLE_ADMIN')")
    public BaseResponse enableMonitorAlert(Integer setType) {
        updateEnableStatus(1,setType);
        return BaseResponse.success();
    }

    @GetMapping("/disableMonitorAlert")
    //@PreAuthorize("hasRole('ROLE_ADMIN')")
    @AllowVisitor(checkToken = false)
    public BaseResponse disableMonitorAlert(Integer setType) {
        updateEnableStatus(0,setType);
        return BaseResponse.success();
    }



    @GetMapping("/device/auditRecord")
    @AllowVisitor(checkToken = false)
    public BaseResponse auditRecord(String recordId,Integer auditStatus){
        MonitorRecord monitorRecord = monitorRecordService.getById(recordId);
        if(monitorRecord==null){
            return BaseResponse.failure("未查询到id为"+recordId+"的报警信息");
        }
        monitorRecord.setAuditStatus(auditStatus);
        monitorRecordService.updateById(monitorRecord);
        return BaseResponse.success("审核成功");
    }
    @AopLog(saveLog = false, name = "查询告警信息分页", platform = "管理后台")
    @PostMapping("/device/getRecordPage")
    @AllowVisitor(checkToken = false)
    public BaseResponse getRecordPage(@RequestBody MonitorRecordVO param) {
        Page<MonitorRecord> page = new Page<>(param.getPageNo(), param.getPageSize());
        page = monitorRecordService.getBaseMapper().getRecordPage(param.getModuleName(),param.getProjectName(), param.getAreaName(),
                param.getSerialNumber(), page);
        return BaseResponse.success(page);
    }

    @GetMapping("/device/getRecordById")
    @AllowVisitor(checkToken = false)
    public  BaseResponse getRecordById(String recordId){
        MonitorRecord monitorRecord = monitorRecordService.getBaseMapper().getRecordById(recordId);
        return BaseResponse.success(monitorRecord);
    }
    private void updateEnableStatus(Integer status,Integer setType) {

        String name;
        switch (setType){
            case 0: name = "temperature";break;
            case 1: name = "humidity";break;
            default: name = "electricity";break;
        }

        MonitorSetting enable = monitorSettingService.getOne(new LambdaQueryWrapper<MonitorSetting>().eq(MonitorSetting::getName, name), false);
        if (enable != null) {
            enable.setInvocation(status);
        } else {
            enable = new MonitorSetting();
            enable.setName(name);
            enable.setEnable(status);
        }
        monitorSettingService.saveOrUpdate(enable);
    };
    //endregion
}
